package cn.itcast.usermanage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mysql.jdbc.StringUtils;

import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@RequestMapping(value="rest/user")
@Controller
public class NewUserController {
	
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value="{id}",method=RequestMethod.GET)
	public ResponseEntity<User> queryUserById(@PathVariable("id")Long id){
		try {
			if(id.longValue()<1){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
			}
			//int i =1/0;
			User user = userService.queryUserById(id);
			if(null == user){
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			}
			return ResponseEntity.ok(user);
		} catch (Exception e) {
			// TODO: handle exception
		}
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);	
		
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public ResponseEntity<Void> addUser(User user){
		try {
			if(StringUtils.isNullOrEmpty(user.getName())){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			//int i =1/0;
			userService.saveUser(user);
			
			return ResponseEntity.status(HttpStatus.CREATED).build();
		} catch (Exception e) {
			// TODO: handle exception
		}
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();	
		
	}
	
	@RequestMapping(method=RequestMethod.PUT)
	public ResponseEntity<Void> updateUser(User user){
		try {
			if(user.getId() == null || user.getId().longValue()<1){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			//int i =1/0;
			userService.updateUser(user);
			//204
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
		} catch (Exception e) {
			// TODO: handle exception
		}
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();	
		
	}
	
	@RequestMapping(method=RequestMethod.DELETE)
	public ResponseEntity<Void> deleteUser(@RequestParam("ids")Long[] ids){
		try {
			if(ids == null || ids.length == 0){
				return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
			}
			//int i =1/0;
			userService.deleteUserById(ids);
			//204
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
		} catch (Exception e) {
			// TODO: handle exception
		}
		//500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();	
		
	}
	
}
